import axios from 'axios'
import { ElMessageBox } from 'element-plus'
import msg from '@/util/Message.ts'
axios.defaults.withCredentials = true




//创建实例
const service = axios.create({
  baseURL: '/api',
  //baseURL: '/api',
    timeout: 1000*60 // request timeout
})

//配置拦截器
service.interceptors.request.use(
    (config) => {
      config.headers['app-path'] = window.location.href; //传到服务器，如果登录后需要重定向等
      config.headers['clinet-type'] = '2'
      return config
    },
    (error) => {
      console.log(error) // for debug
      Promise.reject(error)
    }
)

//处理返回信息
service.interceptors.response.use(
    response => {
      if(response.data.code == 0){
        return response.data;
      }else{
          
          msg.error(response.data.msg)
        return Promise.reject(response.data)
      }
        
    }, error => {
      let status = error.response.status;
      let data = error.response.data;
   
      if (status === 401) { //需要登录
        if (data.errorType === "NOT_LOGIN_CAS") {        
            //发现CAS未登录，跳转到CAS统一登录页面
            location.href = data.casLoginUrl
            return Promise.reject("401");

        }else if(data.errorType === "NOT_LOGIN"){
            //TODO redirect to login page to login
            return Promise.reject("401");
        } 
        else {
            return Promise.reject(error)
        }
      } else {
            ElMessageBox.alert('发生了错误，请刷新页面后重试！', '请求失败')
            return Promise.reject(error)
      }
    });


    
    //封装get、post
    function post<T>(url:string,data_={}): Promise<ResultData<T>>{
       
        return service.post(url,data_);
    }

    function get<T>(url:string,params?:object):Promise<ResultData<T>>{
        return service.get(url,{params});
    }
  
  export default {
    post,get,
  }



  